import 'dart:convert';
import 'package:beautiful_demo/common/beans/ws_bean.dart';
import 'package:beautiful_demo/common/manager/user.dart';
import 'package:beautiful_demo/common/manager/websocket.dart';
import 'package:beautiful_demo/common/res.dart';
import 'package:beautiful_demo/mvc/chat/list/chat_list_bean.dart';
import 'package:beautiful_demo/mvc/chat/list/controller.dart';
import 'package:beautiful_demo/mvc/good/pop/controller.dart';
import 'package:drive/drive.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:keyboard_utils/keyboard_listener.dart' as kl;
import 'package:keyboard_utils/keyboard_utils.dart';
import 'messages_bean.dart';
import 'view.dart';
import 'package:flutter_mvc/flutter_mvc.dart';
import 'controller.dart';

final emoji =
    "😁😂😃😄👿😉😊☺😌😍😏😒😓😔😖😘😚😜😝😞😠😡😢😣😥😨😪😭😰😱😲😳😷😋😗😛🤑🤓😎🤗🙄🤔😩😤🤐🤒😴😀😆😅😇😙😟😕🙁😫😶😐😑😯😦😧😮😵😬🤕😈👻💩💀👽👾👺👹";


class ChatRoomPrivateController extends SecController{
  final ChatRoomController c;

  ChatRoomPrivateController(this.c):super(c);



  void initListener() {
    //消息返回
    WebSocketManager.instance.addListener(WsBean.chat, (result) {
      c.insertMessage(result);
      WebSocketManager.instance.sendMold(WsBean.chatRead, id: c.chatId);
    }, id: c.chatId.toString());
    //得到第一页消息
    WebSocketManager.instance.addListener(WsBean.chatOpen, (result) {
      final message = MessagesBean(const JsonDecoder().convert(result.value));
      c.dataList.clear();
      c.dataList.addAll(message.data);
      c.isMore = c.dataList.isNotEmpty;
      setState();

      Future.delayed(const Duration(milliseconds: 16)).then((value) {
        c.scrollController.jumpTo(c.scrollController.position.maxScrollExtent);
      });
    }, id: c.chatId.toString());
    //分页
    WebSocketManager.instance.addListener(WsBean.chatMore, (result) {
      final message = MessagesBean(const JsonDecoder().convert(result.value));
      c.dataList.insertAll(0, message.data);
      c.isMore = message.data.isNotEmpty;
      setState();
    }, id: c.chatId.toString());

    //键盘处理
    c.idKeyboardListener = c.keyboardUtils.add(
        listener: kl.KeyboardListener(willHideKeyboard: () {
      //判断是否是默认状态-返回
      if (c.keyboardState != KeyboardSpecState.None) return;
      //底部高度0
      c.animBottomHeight(0.0);
      setState();
    }, willShowKeyboard: (double height) {
      ///底部键盘高度
      ///底部状态默认
      c.animBottomHeight(height);
      c.keyboardState = KeyboardSpecState.None;
      setState();
    }));

    c.animController.addStatusListener((status) {
      if (status == AnimationStatus.completed ||
          status == AnimationStatus.dismissed) {
        c.animController.clearListeners();
        c.animController.reset();
      }
    });
  }


  void initEmoji() {
    int length = emoji.length;
    c.listEmoji.clear();
    for (int i = 0; i < length;) {
      final previousCodeUnit = emoji.codeUnitAt(i);
      final offset = isUtf16Surrogate(previousCodeUnit) ? 2 : 1;
      String emo = "";
      for (int j = 0; j < offset; j++) {
        emo += emoji[i + j];
      }
      c.listEmoji.add(emo);
      i += offset;
    }
    setState();
  }


  bool isUtf16Surrogate(int value) {
    return value & 0xF800 == 0xD800;
  }

}

class ChatRoomEventController extends SecController{
  final ChatRoomController c;

  ChatRoomEventController(this.c):super(c);



  void onEmojiClick() {
    if (c.keyboardState == KeyboardSpecState.Emoji) {
      c.keyboardState = KeyboardSpecState.None;
      SystemChannels.textInput.invokeMethod('TextInput.show');
    } else {
      SystemChannels.textInput.invokeMethod('TextInput.hide');
      c.animBottomHeight(234.dp);
      c.keyboardState = KeyboardSpecState.Emoji;
      setState();
    }
  }


  void onEmojiItemClick(String listEmoji) {
    c.textMessageController.text = c.textMessageController.text + listEmoji;
    c.textMessageController.selection = TextSelection(
        baseOffset: c.textMessageController.text.length,
        extentOffset: c.textMessageController.text.length);
  }


  void onSendClick() {
    final text = c.textMessageController.text.trim();
    if (text.isEmpty) return;
    c.textMessageController.clear();
    final bean = WebSocketManager.instance.sendValue(c.chatId, 1, text);
    bean.id=UserManager.instance.data.id;
    c.insertMessage(bean);
    // parentItem.lastMessage = text;
    c.parentController.setState();
  }


  void onMoreClick() {
    final id = c.dataList.first.list.first.id;
    ///如果id==0（刚开始聊天。没有id没有下一页）
    if (id == 0) {
      c.isMore = false;
      setState();
      return;
    }

    WebSocketManager.instance
        .sendMold(WsBean.chatMore, id: c.chatId, value: id.toString());
  }

}
